package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
//urlPatterns设置拦截所有（后面再放行）
@WebFilter(urlPatterns = "/*")
//设置为过滤器拦截所有
public class FilterLogin implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //转成HTTP拿uri和session和下面匹配，
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //匹配uri的对象 用来匹配是否能配的上对象 调用match方法匹配对象
        AntPathMatcher matcher=new AntPathMatcher();
        //拿到uri
        String URI = request.getRequestURI();
        //定义一个字符串数据设置不拦截的资源
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                //放行客户端的登录controller
                "/user/login",
                "/user/sendMsg"};
        //匹配浏览器资源和不拦截的资源能不能匹配的上
        for (String loginUrl : loginUrls) {
            //调用方法是否匹配
            boolean match = matcher.match(loginUrl, URI);
            //拿到session
            //如果匹配放行
            if(match){
                //到本地线程存储可以在别处用
                filterChain.doFilter(request,servletResponse);
                return;
            }
        }
        //看看管理端是否已经登录
        Object employee = request.getSession().getAttribute("employee");
       //已经登录过了直接放行
        if(employee!=null){
            //拿到session
            Long eid = (Long) ((HttpServletRequest) servletRequest).getSession().getAttribute("employee");
            //放到存储数据的线程用base的set方法在那边get
            BaseContext.setCurrentId(eid);
            //放行
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //判断用户端手机号是否已经登录
        Long user = (Long)request.getSession().getAttribute("user");
        if(user!=null){
            //存到 存储线程里
              BaseContext.setCurrentId(user);
            //放行
            filterChain.doFilter(request,servletResponse);
            return;
        }
        //如果走到这就说明成功拦截【前端会自动跳转到相应的页面】
        R<Object> notlogin = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(notlogin);
        servletResponse.getWriter().write(jsonString);
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
